package edu.gyc.stu.controller;

import edu.gyc.stu.dao.StuDao;
import edu.gyc.stu.model.Student;
import edu.gyc.stu.util.ConnectPool;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet(name = "StuServlet",urlPatterns = {"/stu"})
public class StuServlet extends HttpServlet {

    private static Logger logger = Logger.getLogger(StuServlet.class.getName());

    private ConnectPool connectPool;
    private StuDao stuDao;


    @Override
    public void init() throws ServletException {
        super.init();
        connectPool = (ConnectPool) getServletContext().getAttribute("pool");
        stuDao = new StuDao(connectPool);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String method = request.getParameter("method");
        String path = "stu?method=list";
        Student student = new Student();
        try {
            BeanUtils.populate(student, request.getParameterMap());
            logger.info(student.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        switch (method) {
            case "add":
                if (stuDao.addStu(student)) {
                    logger.info("添加 student ok!");
                }
                break;

            case "update":
                if (stuDao.updateStu(student)) {
                    logger.info("更新"+student.getId()+ " 号学生成功！");
                }
                break;
        }

        response.sendRedirect(path);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        StuDao dao = new StuDao(connectPool);
//        request.setAttribute("stus", dao.getAllStu());
//        request.getRequestDispatcher("admin/student.jsp").forward(request, response);
//增加method字段，用来复用doGet方法，get请求不仅仅为查询学生服务
        String method = request.getParameter("method");
        if (method == null) {
            method = "list";
        }
        String spage = request.getParameter("page");

        if (spage == null || spage == "") {
            spage = "1";
        }
        int page = Integer.parseInt(spage);
        int pageSize=2;
        int totalPages = stuDao.getTotalPages(pageSize);

        Integer n= (Integer) request.getSession().getAttribute("currentPage");

        if (n != null && n > 0) {
            if (page == -1) {
                page =n-1;
                if (page < 1) {
                    page=1;
                }

            } else if (page == 9999) { // 页数9999表示下一页的请求，数据应该不会有9999页
                page=n+1;
                if (page > totalPages) {
                    page=totalPages;
                }
            }
        }
        //把当前页数值保存到session中，给上一页和下一页用
       request.getSession().setAttribute("currentPage",page);

        String path = "";
        switch (method) {
            case "list":
                request.setAttribute("stus", stuDao.getStuPage(page, pageSize));
                request.setAttribute("totalPages",totalPages);
                path = "admin/student.jsp";
                break;
            case "del":
                int id = Integer.parseInt(request.getParameter("id"));
                path = "stu?method=list";
                if (stuDao.delStu(id)) {

                    logger.info("del "+id+" ok!");
                } else {

                    logger.info("del "+id+" fail!");
                }

                break;
        }

        request.getRequestDispatcher(path).forward(request, response);
    }
}
